import React, {Component} from 'react';
import {View, Text, StatusBar, ImageBackground,Image, TextInput,TouchableOpacity} from 'react-native'
import SafeAreaViewPlus from "../../common/SafeAreaViewPlus";
import styles from "./styles";
import Fontisto from "react-native-vector-icons/Fontisto";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import {Constant, StylesConstant} from "../../common/Constant";
import StorageUtil from "../../utils/StorageUtil";
import ToastUtil from "../../utils/ToastUtil";

import {BASE_URL} from '../../common/BASE_URL';


class Login extends Component {

    constructor() {
        super();
        this.state = {
            username: '',
            password: '',
            isSave: false
        }
    }
    componentDidMount(){
        this._initUsername();
    }

    async _initUsername() {
        const name = await StorageUtil.get(Constant.localUsername);
        const pwd = await StorageUtil.get(Constant.localPassword);

        if (name || pwd) {
            const user = {};
            if (name) {
                user.username = name;
            }
            if (pwd) {
                user.password = pwd;
                user.isSave = true
            }
            this.setState(user);
        }
    }

    checkboxChange(){
        this.setState({
            isSave: !this.state.isSave
        })
    }
    submitLogin(){
        const {navigation} = this.props;
        let  {username, password} = this.state;
        if (!username) {
            ToastUtil.info('请输入用户名');
            return;
        }
        if (!password) {
            ToastUtil.info('请输入密码');
            return;
        }
        // username="巡查中队队员1"
        const url = BASE_URL.apiBaseUrl + '/auth/loginNoCode'
        const toastKey = ToastUtil.loading('登录中...');
        fetch(url, {
            headers: {
                // 'Content-Type': 'application/x-www-form-urlencoded',
                // 'Content-Type': 'multipart/form-data"',
                "Accept": "application/json",
                "Content-Type": 'application/json',
                Authorization: 'Bearer ',
            },
            method: 'POST',
            body: JSON.stringify({
                username, password
            })
        })
            .then(function (response) {
                // console.log(response)
                return response.json();
            })
            .then((result) => {
                ToastUtil.remove(toastKey);
                console.log(result)
                if (!result.status) {
                    // 缓存TOKEN
                    const {token,user} = result
                    const realUser = user.user
                    console.log(realUser.nickName)
                    console.log(realUser.id)
                    StorageUtil.save(Constant.token, token);
                    StorageUtil.save(Constant.userId, realUser.id);
                    StorageUtil.save(Constant.userName, realUser.nickName);
                    StorageUtil.save(Constant.avatarPath, realUser.avatarPath);
                    StorageUtil.save(Constant.userInfo, realUser);

                    // 账号密码
                    StorageUtil.save(Constant.localUsername, username);
                    StorageUtil.save(Constant.localPassword, this.state.isSave?password: '');
                    navigation.navigate('Init');
                } else {
                    const msg = result
                        ? result.message
                            ? result.message || '网络异常，请检查网络连接'
                            : '网络异常，请检查网络连接'
                        : '网络异常，请检查网络连接';
                    ToastUtil.info(msg);
                }
            })
            .catch((e) => {
                console.log('error: ',e)
                ToastUtil.info('网络异常，请检查网络连接');
                ToastUtil.remove(toastKey);
            });

    }
    render() {
        const iconColor = StylesConstant.themeIconColor;
        return (
            <SafeAreaViewPlus>
                <KeyboardAwareScrollView keyboardShouldPersistTaps={'always'}>
                <ImageBackground style={styles.loginBgImage} source={require('../../assets/login/login_bg.png')} >
                    <StatusBar backgroundColor="#ff0000"
                       translucent={true}
                       hidden={true}
                       animated={true}
                    />
                    <View style={styles.loginPanel}>
                        <View style={{alignItems: 'center',marginBottom: 50}}>
                            <Image source={require('../../assets/login/logo.png')} style={{width: 70,height: 70}} />
                            <Text style={{color: '#fff',fontSize: 24,marginTop:5}}>综合执法移动平台</Text>
                        </View>
                        <View style={[styles.inputPanel,{marginBottom: 30}]}>
                            <Image source={require('../../assets/login/user.png')} style={{width: 15,height: 15}} />
                            <Text  style={styles.splitClass}/>
                            <TextInput
                                style={styles.textInput}
                                multiline={false}
                                autoCapitalize={'none'} // 首字母不大写
                                selectionColor={'#eee'}
                                placeholder={'请输入用户名'}
                                placeholderTextColor={'#a6a6a6'}
                                clearButtonMode={'always'}
                                underlineColorAndroid={'transparent'}
                                defaultValue={this.state.username}
                                onChangeText={(text) => {
                                    this.setState({
                                        username: text,
                                    });
                                }}
                            />
                        </View>
                        <View style={styles.inputPanel}>
                            <Image source={require('../../assets/login/password.png')} style={{width: 15,height: 15}} />
                            <Text  style={styles.splitClass}/>
                            <TextInput
                                style={styles.textInput}
                                multiline={false}
                                password={true}
                                secureTextEntry={true}
                                defaultValue={this.state.password}
                                selectionColor={'#eee'}
                                placeholder={'请输入密码'}
                                placeholderTextColor={'#a6a6a6'}
                                clearButtonMode={'always'}
                                underlineColorAndroid={'transparent'}
                                onChangeText={(text) => {
                                    this.setState({
                                        password: text,
                                    });
                                }}
                            />
                        </View>
                        <View style={{alignItem:'flex-end',justifyContent: 'flex-end',flexDirection: 'row',paddingTop: 10}}>
                            <TouchableOpacity
                                style={{flexDirection: 'row',alignItems: 'center'}}
                                activeOpacity={0.5}
                                onPress={() => this.checkboxChange()}>
                                <Fontisto
                                    style={{marginTop: 2}}
                                    name={this.state.isSave ? 'checkbox-active' : 'checkbox-passive'}
                                    size={14}
                                    color={iconColor}
                                />
                                <Text style={{color: '#Fff',paddingLeft:5}}>记住密码</Text>
                            </TouchableOpacity>
                        </View>
                        <TouchableOpacity
                            style={[styles.inputPanel,{backgroundColor: '#fff',flexDirection: 'row',paddingLeft: 0,justifyContent: 'center',marginTop: 10}]}
                            onPress={()=>this.submitLogin()}
                        >
                            <Text>登录</Text>
                        </TouchableOpacity>
                    </View>

                </ImageBackground>
                </KeyboardAwareScrollView>
            </SafeAreaViewPlus>
        );
    }
}
export default Login;
